package com.xxx.config;

import com.xxx.config.api.AuditAware;
import com.xxx.config.api.ReturnResult;
import com.xxx.config.exception.GenExceptCode;
import com.xxx.util.jwt.JwtUtil;
import com.xxx.util.jwt.PassToken;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.http.HttpStatus;

import java.lang.reflect.Method;

/**
 * 自定义拦截器实现
 */
public class RequestFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) {
        // 在这里进行拦截和处理操作
        // 可以获取请求的信息，进行身份验证、参数校验等操作
        // 如果需要终止请求并返回响应，可以使用requestContext.abortWith方法

        Method method = resourceInfo.getResourceMethod();
        if (method != null && method.isAnnotationPresent(PassToken.class)) {
            PassToken aspect = method.getAnnotation(PassToken.class);
            if (aspect != null && aspect.canPass()) {
                return;
            }
        }

        String headerToken = JwtUtil.getJwtFromHeader(requestContext);
        String urlToken = JwtUtil.getJwtFromUrl(requestContext);

        if (StringUtils.isEmpty(headerToken) && StringUtils.isEmpty(urlToken)) {
            requestContext.abortWith(Response.ok(new ReturnResult(GenExceptCode.Operation_Denial.name(), "操作被拒！"))
                    .status(HttpStatus.UNAUTHORIZED_401).type(MediaType.APPLICATION_JSON_TYPE).build());
        } else {
            if (StringUtils.isEmpty(headerToken)) {
                if (StringUtils.isEmpty(urlToken)) {
                    requestContext.abortWith(Response.ok(new ReturnResult(GenExceptCode.Operation_Denial.name(), "操作被拒！"))
                            .status(HttpStatus.UNAUTHORIZED_401).type(MediaType.APPLICATION_JSON_TYPE).build());
                } else {
                    AuditAware.setUserId(JwtUtil.getUserIdFromToken(urlToken));
                }
            } else {
                AuditAware.setUserId(JwtUtil.getUserIdFromToken(headerToken));
            }
        }
    }
}
